﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Dukou.Search
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class PropertySearchResultItem : AbstractSearchResultItem
    {
        private static IDictionary<Type, IList<string>> typedFieldNames = new Dictionary<Type, IList<string>>();

        private IEnumerable<string> m_fieldNames;

        private object m_data;

        public PropertySearchResultItem(object data)
        {
            Type dataType = data.GetType();
            if (!typedFieldNames.ContainsKey(dataType))
            {
                lock (typedFieldNames)
                {
                    if (!typedFieldNames.ContainsKey(dataType))
                    {
                        IList<string> fieldNames = new List<string>();
                        foreach (PropertyInfo prop in dataType.GetProperties())
                        {
                            fieldNames.Add(prop.Name);
                        }
                        typedFieldNames.Add(dataType, fieldNames);
                        this.m_fieldNames = fieldNames;
                    }
                }
            }
            else
            {
                this.m_fieldNames = typedFieldNames[dataType];
            }
            this.m_data = data;
        }

        public override object UnderlayerObject
        {
            get 
            { 
                return this.m_data; 
            }
        }

        public override IEnumerable<string> FieldNames
        {
            get 
            { 
                return this.m_fieldNames; 
            }
        }

        public override object GetValue(string fieldName)
        {
            try
            {
                return this.m_data.GetType().GetProperty(fieldName).GetValue(this.m_data, null);
            }
            catch
            {
                return null;
            }
        }
    }
}
